package cn.edu.xaut.mybatisers.mall.Controller;

import cn.edu.xaut.mybatisers.mall.Entity.AReturnDataStruct;
import cn.edu.xaut.mybatisers.mall.Entity.Bill;
import cn.edu.xaut.mybatisers.mall.Entity.OrderOneByOne;
import cn.edu.xaut.mybatisers.mall.Exception.ExceptionEntity.BillStatusException;
import cn.edu.xaut.mybatisers.mall.Exception.ExceptionEntity.ParametersIncompleteException;
import cn.edu.xaut.mybatisers.mall.ServiceImp.BillServiceImp;
import cn.edu.xaut.mybatisers.mall.tool.AReturnStructFactory;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiOperation;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.sql.SQLException;
import java.util.*;
import java.util.regex.Pattern;

@Controller
@RequestMapping("/bill")
@SuppressWarnings("all")
public class BillController {

    @Autowired
    BillServiceImp billServiceImp;

    @ApiOperation("根据订单号查询订单")
    @RequestMapping(value = "/getByOrderNumber", method = RequestMethod.GET)
    @ResponseBody
    public AReturnDataStruct getBillByOrderNumber(Bill bill) throws ParametersIncompleteException, SQLException {
        if (bill.getOrder_number() == null){
            throw new ParametersIncompleteException("order number");
        }
        ArrayList<Bill> bill_return = billServiceImp.getBillByOrderNumber(bill);
        AReturnDataStruct aReturnDataStruct = new AReturnDataStruct();
        if (bill_return.size() <= 0){
            aReturnDataStruct.setMessage("订单号无效");
            aReturnDataStruct.setResult(false);
            aReturnDataStruct.setCode(200);
        }else {
            aReturnDataStruct.setCode(200);
            aReturnDataStruct.setData(bill_return.get(0));
            aReturnDataStruct.setResult(true);
        }
        return aReturnDataStruct;
    }


    @ApiOperation("创建订单")
    @RequestMapping(value = "/createOrder", method = RequestMethod.POST)
    @ResponseBody
    public AReturnDataStruct createOrder(@RequestBody Bill bill, HttpSession session) throws SQLException, ParametersIncompleteException {
        if (bill.getAddress_city() == null || bill.getAddress_county() == null ||
            bill.getAddress_location() == null || bill.getAddress_province() == null)
            throw new ParametersIncompleteException("地址不完整");
        if (bill.getConsignee() == null)
            throw new ParametersIncompleteException("收货人");
        bill.setConsumer_id((Integer) session.getAttribute("consumer_id"));
        String orderNumber = billServiceImp.createOrder(bill);
        return AReturnStructFactory.returnDataStructFactory(true, "创建成功", 200, orderNumber);
    }

    @ApiOperation("修改订单")
    @RequestMapping(value = "/alterOrder", method = RequestMethod.POST)
    @ResponseBody
    public Boolean alterOrder(@RequestBody Bill bill) throws ParametersIncompleteException, SQLException, BillStatusException {
        if (bill.getOrder_number() == null){
            throw new ParametersIncompleteException("order_number");
        }
        if (bill.getBillStatus()!= 0 && !bill.statusMapper.containsKey(bill.getBillStatus())) {
            throw new ParametersIncompleteException("订单状态");
        }
        if (bill.getTeleNumber() != null && !Pattern.compile("^1[3,5]\\d{9}||18[6,8,9]\\d{8}$").matcher(bill.getTeleNumber()).matches()){
            throw new ParametersIncompleteException("手机号");
        }
        return billServiceImp.alterBill(bill);
    }

    @ApiOperation("删除订单")
    @RequestMapping(value = "/deleteOrder", method = RequestMethod.GET)
    @ResponseBody
    public AReturnDataStruct deleteOrder(Bill bill) throws ParametersIncompleteException, SQLException, BillStatusException {
        if (bill.getOrder_number() == null){
            throw new ParametersIncompleteException("order_number");
        }
        int result = billServiceImp.deleteOrder(bill);
        AReturnDataStruct return_data = new AReturnDataStruct();
        return_data.setResult(result > 0);
        return_data.setCode(200);
        return_data.setData(result > 0 ? "删除成功" : "没有该订单");
        return return_data;
    }

    @ApiOperation("提交订单")
    @RequestMapping(value = "/submitBill", method = RequestMethod.GET)
    @ResponseBody
    public AReturnDataStruct submitBill(String orderNumber) throws SQLException {
        Map<String, Object> data = billServiceImp.submitBill(orderNumber);
        AReturnDataStruct return_data = new AReturnDataStruct();
        if ((Boolean) data.get("result")){
            return_data.setResult(true);
            return_data.setCode(200);
            return_data.setData("提交成功");
        }else {
            return_data.setResult(false);
            return_data.setCode(200);
            return_data.setData("提交失败, [ "+ data.get("lackCommodity_name") + "] 库存不足");
        }
        return return_data;
    }

    @ApiOperation("根据用户id查询所有订单，并分页返回")
    @RequestMapping("/allBillByPage")
    @ResponseBody
    public PageInfo<Bill> getAllBillByPage(
            @RequestParam(value = "pageNum", required = false, defaultValue = "1") int pageNum,
            @RequestParam(value = "pageSize", required = false, defaultValue = "5") int pageSize,
            HttpSession session
    ) throws SQLException {
        int consumer_id = (int)session.getAttribute("consumer_id");
        return billServiceImp.getAllBillByPage(consumer_id, pageNum, pageSize);
    }

    @ApiOperation("给订单里面加商品，也就是从购物车里面提交商品到订单里面")
    @RequestMapping(value = "/addCommodityToBill", method = RequestMethod.POST)
    @ResponseBody
    public AReturnDataStruct addCommodityToBill(@RequestBody JSONObject jsonObject) throws ParametersIncompleteException, SQLException, BillStatusException {
        double totalPrice = Double.valueOf((String) jsonObject.get("totalPrice"));
        List<JSONObject> jsonObjects = (List<JSONObject>) jsonObject.get("commodityData");
        List<OrderOneByOne> orderOneByOnes = new ArrayList<>();
        Iterator<JSONObject> it = jsonObjects.iterator();
        OrderOneByOne o;
        JSONObject j;
        while (it.hasNext()){
            o = new OrderOneByOne();
            j = it.next();
            o.setOrder_number((String) j.get("order_number"));
            o.setCommodity_id((Integer) j.get("commodity_id"));
            o.setDealPrice(5.00);
            o.setBuy_number((Integer) j.get("buy_number"));
            orderOneByOnes.add(o);
        }
        String orderNumber = orderOneByOnes.get(0).getOrder_number();
        Bill bill = new Bill();
        bill.setOrder_number(orderNumber);
        bill.setTotalPrice((float) totalPrice);
        billServiceImp.alterBill(bill);
        bill = null;
        billServiceImp.addCommodityToOrder(orderOneByOnes);
        return AReturnStructFactory.returnDataStructFactory(true, "订单生成, 请尽快支付", 200, orderNumber);
    }
    /**
     * 结算购物车生成订单的逻辑：
     * 1. 请求[创建订单的接口]传入电话地址收件人, 获得订单号
     * 2. 请求[购物车结算的接口]传入订单号, 获得返回数据
     * 3. 请求[给订单里面添加商品的接口]传入2返回的数据
     * */

    @ApiOperation("根据用户id与订单状态查询订单")
    @RequestMapping(value = "/findOrderByStatus", method = RequestMethod.POST,consumes = "application/json;charset=UTF-8")
    @ResponseBody
    PageInfo<Bill> findBillByStatus(@RequestBody JSONObject jsonObject, HttpSession session) throws SQLException, ParametersIncompleteException {
        Integer pageNum, pageSize = null;
        if (!jsonObject.has("billStatus"))
            throw new ParametersIncompleteException("bill Status");
        Integer billStatus = (Integer) jsonObject.get("billStatus");
        if (jsonObject.has("pageNum")) {
            pageNum = (Integer) jsonObject.get("pageNum");
        } else {
            pageNum = 1;
        }
        if (jsonObject.has("pageSize")) {
            pageSize = (Integer) jsonObject.get("pageSize");
        } else {
            pageSize = 5;
        }
        return billServiceImp.findBillByStatus((Integer) session.getAttribute("consumer_id"), billStatus,  pageNum, pageSize);
    }

    @ApiOperation("查询订单里面的所有商品")
    @RequestMapping(value = "/getCommodities", method = RequestMethod.GET)
    @ResponseBody
    public AReturnDataStruct getCommodities(Bill bill) throws ParametersIncompleteException, SQLException {
        if (bill.getOrder_number() == null)
            throw new ParametersIncompleteException("订单号不完整");
        return AReturnStructFactory.returnDataStructFactory(true, "查询成功", 200, billServiceImp.getCommodities(bill.getOrder_number()));
    }

    @ApiOperation("给订单里面的商品评论")
    @RequestMapping(value = "/comment", method = RequestMethod.POST)
    @ResponseBody
    public AReturnDataStruct comment(@RequestBody OrderOneByOne orderOneByOne) throws ParametersIncompleteException, SQLException {
        if (orderOneByOne.getOrder_number() == null){
            throw new ParametersIncompleteException("订单号不完整");
        }
        if (orderOneByOne.getCommodity_id() <= 0){
            throw new ParametersIncompleteException("商品id不完整");
        }
        if (orderOneByOne.getEvaluate() == null){
            throw new ParametersIncompleteException("请填写评论");
        }
        billServiceImp.comment(orderOneByOne);
        AReturnDataStruct aReturnDataStruct = new AReturnDataStruct();
        aReturnDataStruct.setMessage("评论成功");
        aReturnDataStruct.setCode(200);
        aReturnDataStruct.setResult(true);
        return aReturnDataStruct;
    }

    @ApiOperation("删除订单里面的商品评论")
    @RequestMapping(value = "/deleteComment", method = RequestMethod.POST)
    @ResponseBody
    public AReturnDataStruct deleteComment(@RequestBody OrderOneByOne orderOneByOne) throws ParametersIncompleteException, SQLException {
        if (orderOneByOne.getOrder_number() == null){
            throw new ParametersIncompleteException("订单号不完整");
        }
        if (orderOneByOne.getCommodity_id() <= 0){
            throw new ParametersIncompleteException("商品id不完整");
        }
        billServiceImp.deleteComment(orderOneByOne);
        AReturnDataStruct aReturnDataStruct = new AReturnDataStruct();
        aReturnDataStruct.setMessage("删除成功");
        aReturnDataStruct.setCode(200);
        aReturnDataStruct.setResult(true);
        return aReturnDataStruct;
    }
}